import 'dart:async';
import 'dart:collection';
import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:changxindianzishangwu/cache/local_cache.dart';
import 'package:changxindianzishangwu/dao/common_language_dao.dart';
import 'package:changxindianzishangwu/dao/emoji_list_dao.dart';
import 'package:changxindianzishangwu/else/lib/common/index.dart';
import 'package:changxindianzishangwu/model/collect_list_model.dart';
import 'package:changxindianzishangwu/model/common_language_model.dart';
import 'package:changxindianzishangwu/pages/message/message_icon_page.dart';
import 'package:changxindianzishangwu/pages/my/collect_page.dart';
import 'package:changxindianzishangwu/pages/my/settings/common_language_page.dart';
import 'package:changxindianzishangwu/provider/currentMessageList.dart';
import 'package:changxindianzishangwu/util/colors.dart';
import 'package:changxindianzishangwu/util/time_util.dart';
import 'package:changxindianzishangwu/util/toast.dart';
import 'package:changxindianzishangwu/widget/message/message_body_widget.dart';
import 'package:emoji_picker_flutter/emoji_picker_flutter.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_plugin_record/flutter_plugin_record.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:get/get_utils/src/platform/platform.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';
import 'package:tencent_im_sdk_plugin/enum/V2TimAdvancedMsgListener.dart';
import 'package:tencent_im_sdk_plugin/enum/offlinePushInfo.dart';
import 'package:tencent_im_sdk_plugin/manager/v2_tim_manager.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_callback.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_conversation.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_message.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_message_receipt.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_user_full_info.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_value_callback.dart';
import 'package:tencent_im_sdk_plugin/tencent_im_sdk_plugin.dart';
import 'package:video_player/video_player.dart';
import 'package:video_thumbnail/video_thumbnail.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

import 'friend_info_setting_page.dart';

class MessageC2cPage extends StatefulWidget {
  final String conversationID;
  final String nickName;
  final int type;
  final String userID;
  final String faceUrl;
  MessageC2cPage(
      this.nickName, this.type, this.userID, this.faceUrl, this.conversationID);

  @override
  _MessageC2cPageState createState() => _MessageC2cPageState(conversationID);
}

class _MessageC2cPageState extends State<MessageC2cPage>
    with AutomaticKeepAliveClientMixin {
  String conversationID;
  _MessageC2cPageState(this.conversationID);

  /// 文本组件控制器
  TextEditingController _textEditingController = TextEditingController();

  /// 会话实体
  V2TimConversation _conversation;
  int type = 1;
  String lastMessageId = '';
  String userID = '';
  String groupID = '';
  Icon righTopIcon = Icon(Icons.add);
  bool isreverse = true;

  /// 消息列表
  List<V2TimMessage> _messages = [];

  /// 用户信息
  V2TimUserFullInfo _selfUser;

  /// 临时目录
  String _tempPath;
  String bottomIcon = "images/message/表情.png";
  final _focusNode = FocusNode();
  bool flag = false;
  FlutterPluginRecord recordPlugin = new FlutterPluginRecord();
  bool soundFlag = false;
  String filePath = "";
  int soundDur = 0;
  bool flags = false;
  bool flagVoices = false;
  bool flagVoices2 = false;
  String _name;
  final List<String> actions = [
    '复制',
    '转发',
    '收藏',
    '删除',
    '多选',
  ];
  List leftSpots = [];
  OverlayEntry overlayEntry;
  String voiceIco = "images/voice_volume_1.png";
  String leftIcon = "images/message/语音.png";
  bool flagBootom = true;
  bool isRecording = false;
  bool isSend = true;
  int count = 40;
  bool headerFlag = true;
  ScrollController _controller = new ScrollController();
  List<V2TimMessage> someMessage = [];
  bool value = false;
  bool checkMessage = true;
  bool videoColor = true;
  List<Widget> widgetElse = [];
  List<Widget> widgetData = [];
  List emojiId = [];
  bool a = false;
  bool favorite = true;
  List<Widget> sheetList = [];
  List<CommonLanguageBean> _lists = [];
  bool emojo = true;
  List<CommonLanguageBean> _leaveLists = [];

  @override
  void initState() {
    super.initState();
    getDataList();
    _getConversion();
    _listing();
    _name = widget.nickName;
    _controller.addListener(() {
      if (_controller.position.pixels == _controller.position.maxScrollExtent) {
        //_loadMoreData();
      }
    });
    _initRecordMp3();

    _loadTempPath();

    _focusNode.addListener(() {
      print("Has focus: ${_focusNode.hasFocus}");
      if (_focusNode.hasFocus) {
        setState(() {
          _controller.jumpTo(_controller.position.minScrollExtent);
          bottomIcon = "images/message/表情.png";
          favorite = true;
          flag = false;
          flagBootom = false;
          emojo = true;
        });
      } else {
        setState(() {
          // bottomIcon = "images/message/表情.png";
          flagBootom = true;
        });
      }
    });

    ///初始化方法的监听
    recordPlugin.responseFromInit.listen((data) {
      if (data) {
        print("初始化成功");
      } else {
        print("初始化失败");
      }
    });
    getData();

    /// 开始录制或结束录制的监听
    recordPlugin.response.listen((data) async {
      if (data.msg == "onStop") {
        ///结束录制时会返回录制文件的地址方便上传服务器
        print("onStop  文件路径" + data.path);
        filePath = data.path;
        print("onStop  时长 " + data.audioTimeLength.toString());
        soundDur = int.parse(data.audioTimeLength
            .toString()
            .substring(0, data.audioTimeLength.toString().indexOf(".")));
        await _soundSelect();
      } else if (data.msg == "onStart") {
        print("onStart --");
      } else {
        print("--" + data.msg);
      }
    });

    recordPlugin.responseFromAmplitude.listen((data) {
      var voiceData = double.parse(data.msg);
      setState(() {
        if (voiceData > 0 && voiceData < 0.1) {
          voiceIco = "images/voice_volume_2.png";
        } else if (voiceData > 0.2 && voiceData < 0.3) {
          voiceIco = "images/voice_volume_3.png";
        } else if (voiceData > 0.3 && voiceData < 0.4) {
          voiceIco = "images/voice_volume_4.png";
        } else if (voiceData > 0.4 && voiceData < 0.5) {
          voiceIco = "images/voice_volume_5.png";
        } else if (voiceData > 0.5 && voiceData < 0.6) {
          voiceIco = "images/voice_volume_6.png";
        } else if (voiceData > 0.6 && voiceData < 0.7) {
          voiceIco = "images/voice_volume_7.png";
        } else if (voiceData > 0.7 && voiceData < 1) {
          voiceIco = "images/voice_volume_7.png";
        } else {
          voiceIco = "images/voice_volume_1.png";
        }
        if (overlayEntry != null) {
          overlayEntry.markNeedsBuild();
        }
      });

      print("振幅大小   " + voiceData.toString() + "  " + voiceIco);
    });
    recordPlugin.responsePlayStateController.listen((data) {
      print("播放路径   " + data.playPath);
      print("播放状态   " + data.playState);
      if (data.playState == "complete") {
        _messages.forEach((element) {
          element.isPlay = false;
        });
        setState(() {});
      }
    });

    getLeaveData();
  }

  ///收藏表情数据
  getData() async {
    widgetData = [];
    widgetData.add(InkWell(
      onTap: () {
        setState(() {
          emojo = true;
          favorite = true;
          flag = false;
          bottomIcon = "images/message/表情.png";
          leftIcon = "images/message/语音.png";
          soundFlag = false;
        });
        Get.to(() => MessageIconPage());
      },
      child: Container(
        height: 55.w,
        width: 55.w,
        margin: EdgeInsets.only(left: 18.w, top: 15),
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(6),
            border: Border.all(
                width: 0.3,
                color: ZdColor.rgba(214, 214, 214, 1),
                style: BorderStyle.solid)),
        child: Icon(
          Icons.add,
          color: ZdColor.rgba(153, 153, 153, 1),
        ),
      ),
    ));
    CollectListModel collectListModel =
        await EmojiListDao.getEmojiList(getUserInfo().userId);
    if (collectListModel.resultCode == 1) {
      collectListModel.data.forEach((element) {
        widgetData.add(
          InkWell(
              onTap: () async {
                V2TimValueCallback<V2TimMessage> res = await TencentImSDKPlugin
                    .v2TIMManager
                    .getMessageManager()
                    .sendCustomMessage(
                      data: element.url,
                      extension: "images",
                      receiver: _conversation.userID,
                    );
                List<V2TimMessage> list = new List.empty(growable: true);
                V2TimMessage msg = res.data;
                list.add(msg);
                Provider.of<CurrentMessageListModel>(context, listen: false)
                    .addMessage(_conversation.conversationID, list);
                _onLoadMessages();
              },
              child: Container(
                  height: 55.w,
                  width: 55.w,
                  alignment: Alignment.topRight,
                  margin: EdgeInsets.only(left: 18.w, top: 15),
                  decoration: BoxDecoration(
                      image: DecorationImage(
                          image: CachedNetworkImageProvider(
                            element.url,
                          ),
                          fit: BoxFit.cover),
                      borderRadius: BorderRadius.circular(6),
                      border: Border.all(
                          width: 0.3,
                          color: ZdColor.rgba(214, 214, 214, 1),
                          style: BorderStyle.solid)),
                  child: Text(""))),
        );
      });
    }
    setState(() {});
  }

  ///常用语弹出层
  Future _openModalBottomSheet() async {
    await getDataList();
    print(1);
    final option = await showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return Container(
            height: 460.0,
            child: Column(
              children: <Widget>[
                ListTile(
                  leading: InkWell(
                    onTap: () {
                      Navigator.pop(context, '常用语');
                      Get.to(() => CommonLanguagePage(3));
                    },
                    child: Container(
                      height: 40,
                      width: 40,
                      child: Icon(
                        Icons.add_circle_outline,
                        size: 20,
                      ),
                    ),
                  ),
                  title: Text(
                    '常用语',
                    textAlign: TextAlign.center,
                    style: TextStyle(
                        fontSize: 18.sp, color: ZdColor.rgba(51, 51, 51, 1)),
                  ),
                  onTap: () {
                    //_photoSelect();
                    Navigator.pop(context, '常用语');
                  },
                  trailing: InkWell(
                    onTap: () {
                      //_photoSelect();
                      Navigator.pop(context, '常用语');
                    },
                    child: Icon(
                      Icons.clear,
                      size: 20,
                    ),
                  ),
                ),
                Divider(
                  height: 1,
                  indent: ScreenUtil().setWidth(10),
                  color: Color.fromRGBO(248, 248, 248, 1),
                  thickness: ScreenUtil().setHeight(1),
                ),
                Expanded(
                  child: ListView(
                    children: sheetList,
                  ),
                ),
              ],
            ),
          );
        });
    print(option);
  }

  ///常用语数据 点击层
  getDataList() async {
    sheetList = [];
    print('userId:${getUserInfo().userId}');
    _lists.clear();
    LinkedHashMap hashMap = await CommonLanguageDao.getData(3);
    if (!hashMap.containsKey("data")) {
      return;
    }
    CommonLanguageModel commonLanguageModel =
        CommonLanguageModel.fromJson(hashMap);

    if (mounted)
      setState(() {
        _lists.addAll(commonLanguageModel.data);
      });
    if (_lists.length > 0) {
      _lists.forEach((element) {
        sheetList.add(
          ListTile(
            title: Text(
              element.context ?? "",
              textAlign: TextAlign.left,
              style: TextStyle(
                fontSize: 15.sp,
              ),
            ),
            onTap: () {
              getDataList();
              _sendMessage(element.context ?? "123");
              Navigator.pop(context, '取消');
              // _imagesSelect();
            },
          ),
        );
        sheetList.add(
          Divider(
            height: 1,
            indent: 15.w,
            color: ZdColor.rgba(245, 245, 245, 1),
            thickness: 1.w,
            endIndent: 15.w,
          ),
        );
      });
    }
  }

  ///表情选择
  _onEmojiSelected(Emoji emoji) {
    _textEditingController
      ..text += emoji.emoji
      ..selection = TextSelection.fromPosition(
          TextPosition(offset: _textEditingController.text.length));
  }

  ///表情发送事件
  _onBackspacePressed() {
    _textEditingController
      ..text = _textEditingController.text.characters.skipLast(1).toString()
      ..selection = TextSelection.fromPosition(
          TextPosition(offset: _textEditingController.text.length));
  }

  //todo 此处需要从缓存获取
  ///离线回复数据
  getLeaveData() async {
    print('userId:${getUserInfo().userId}');
    _lists.clear();
    LinkedHashMap hashMap = await CommonLanguageDao.getData(2);
    if (!hashMap.containsKey("data")) {
      return;
    }
    CommonLanguageModel commonLanguageModel =
        CommonLanguageModel.fromJson(hashMap);

    if (mounted) _leaveLists.addAll(commonLanguageModel.data);
  }

  ///离线回复事件
  sendLeaveData() {
    if (getUserSayHello() == 2 || getUserSayHello() == 3) {
      //
      if (_leaveLists.length > 0) {
        _leaveLists.forEach((element) {
          _sendMessage(element.context);
        });
      } else {
        _sendMessage("他/她可能离开了一会～");
      }
    } else {}
  }

  ///删除本地聊天记录
  void deleteMessageFromLocalStorage(String msgId) async {
    V2TimCallback res = await TencentImSDKPlugin.v2TIMManager
        .getMessageManager()
        .deleteMessageFromLocalStorage(msgID: msgId);
    if (res.code == 0) {
      showToast("删除成功");

      Provider.of<CurrentMessageListModel>(context, listen: false)
          .deleteMessage(_conversation.conversationID);
      _onLoadMessages();
    } else {
      Provider.of<CurrentMessageListModel>(context, listen: false)
          .deleteMessage(_conversation.conversationID);
      _onLoadMessages();
    }
    print(res.toJson());
  }

  ///关闭键盘
  void closeKeyboard(BuildContext context) {
    FocusScopeNode currentFocus = FocusScope.of(context);

    /// 键盘是否是弹起状态
    if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
      FocusManager.instance.primaryFocus.unfocus();
      setState(() {
        emojo = true;
        favorite = true;
        flag = false;
        bottomIcon = "images/message/表情.png";
        leftIcon = "images/message/语音.png";
        soundFlag = false;
      });
    }
  }

  ///录制
  void _requestAppDocumentsDirectory() {
    setState(() {
      getApplicationDocumentsDirectory().then((value) {
        String nowDataTimeStr = DateUtil.getNowDateMs().toString();

        String wavPath = "";
        if (Platform.isIOS) {
          wavPath = value.path + "/" + nowDataTimeStr + ".wav";
        } else {
          wavPath = value.path + "/" + nowDataTimeStr;
        }
        startByWavPath(wavPath);
      });
    });
  }

  ///初始化语音录制的方法
  void _initRecordMp3() async {
    recordPlugin.init();
  }

  ///开始语音录制的方法
  void start() async {
    recordPlugin.start();
  }

  ///根据传递的路径进行语音录制
  void startByWavPath(String wavPath) async {
    recordPlugin.startByWavPath(wavPath);
  }

  ///停止语音录制的方法
  void stop() {
    recordPlugin.stop();
  }

  ///播放语音的方法
  void play() {
    recordPlugin.play();
  }

  ///播放指定路径录音文件  url为iOS播放网络语音，file为播放本地语音文件
  void playByPath(String path, String type) {
    recordPlugin.playByPath(path, type);
  }

  ///暂停|继续播放
  void pause() {
    recordPlugin.pausePlay();
  }

  void stopPlay() {
    recordPlugin.stopPlay();
  }

  @override
  void dispose() {
    super.dispose();
    stopPlay();
    stop();
    recordPlugin.dispose();
    EasyLoading.dismiss();
    String text = _textEditingController.text.trim();
  }

  /// 加载连目录
  _loadTempPath() async {
    _tempPath = (await getTemporaryDirectory()).path;
    this.setState(() {});
  }

  ///录制语音弹出层
  buildOverLayView(BuildContext context) {
    if (overlayEntry == null) {
      overlayEntry = new OverlayEntry(builder: (content) {
        return Positioned(
          top: MediaQuery.of(context).size.height * 0.5 - 80,
          left: MediaQuery.of(context).size.width * 0.5 - 80,
          child: Material(
            type: MaterialType.transparency,
            child: Center(
              child: Opacity(
                opacity: 0.8,
                child: Container(
                  width: 160,
                  height: 160,
                  decoration: BoxDecoration(
                    color: Color(0xff77797A),
                    borderRadius: BorderRadius.all(Radius.circular(20.0)),
                  ),
                  child: Column(
                    children: <Widget>[
                      Container(
                        margin: EdgeInsets.only(top: 10),
                        child: new Image.asset(
                          voiceIco,
                          width: 100,
                          height: 100,
                          package: 'flutter_plugin_record',
                        ),
                      ),
                      Container(
//                      padding: EdgeInsets.only(right: 20, left: 20, top: 0),
                        child: Text(
                          "手指上滑松开,取消发送",
                          style: TextStyle(
                            fontStyle: FontStyle.normal,
                            color: Colors.white,
                            fontSize: 14,
                          ),
                        ),
                      )
                    ],
                  ),
                ),
              ),
            ),
          ),
        );
      });
      Overlay.of(context).insert(overlayEntry);
    }
  }

  void onRecvC2CReadReceipt(List<V2TimMessageReceipt> list) {
    print('收到了新消息 已读回执');

    list.forEach((element) {
      print("已读回执${element.userID} ${element.timestamp}");
      Provider.of<CurrentMessageListModel>(context, listen: false)
          .updateC2CMessageByUserId(element.userID);
    });
  }

  _listing() {
    V2TIMManager timManager = TencentImSDKPlugin.v2TIMManager;
    timManager.getMessageManager().addAdvancedMsgListener(
          listener: new V2TimAdvancedMsgListener(
            onRecvC2CReadReceipt: (receiptList) {
              //showToast("已读");

              onRecvC2CReadReceipt(receiptList);
            },
            onRecvMessageRevoked: (msgID) async {
              await _onRefresh();
              // showToast("123333");
            },
            onRecvNewMessage: (msg) {
              // sendLeaveData();

              print("新消息！！！：：：：${msg}");
              //  toast("新消息！");

              print("comming！");
              onRecvNewMessage(msg);
            },
            onSendMessageProgress: (message, progress) {
              print("=========================发送中！");

              onSendMessageProgress(message, progress);
            },
          ),
        );
  }

  void onSendMessageProgress(V2TimMessage message, int progress) {
// 消息进度
    String key;
    if (message.groupID == null) {
      key = "c2c_${message.userID}";
    } else {
      key = "group_${message.groupID}";
    }
    try {
      Provider.of<CurrentMessageListModel>(
        context,
        listen: false,
      ).addOneMessageIfNotExits(
        key,
        message,
      );
    } catch (err) {
      print("error $err");
    }
    print(
        "消息发送进度 $progress ${message.timestamp} ${message.msgID} ${message.timestamp} ${message.status}");
  }

  void onRecvNewMessage(V2TimMessage message) {
    try {
      if (message.elemType == 2 && message.customElem.desc == "离线") {
        _loadMoreData();
        setAllReady();
      } else {
        List<V2TimMessage> messageList = List.empty(growable: true);

        messageList.add(message);

        print("c2c_${message.sender}");
        String key;
        if (message.groupID == null) {
          key = "c2c_${message.sender}";
        } else {
          key = "group_${message.groupID}";
        }
        print("conterkey_$key");
        Provider.of<CurrentMessageListModel>(context, listen: false)
            .addMessage(_conversation.conversationID, messageList);

        Map<String, List<V2TimMessage>> _messageMap =
            Provider.of<CurrentMessageListModel>(context, listen: false)
                .messageMap;
        setState(() {
          _messages = _messageMap[_conversation.conversationID];
        });
        setAllReady();
      }
    } catch (err) {
      print(err);
    }
  }

  ///获取会话列表
  _getConversion() async {
    V2TimValueCallback<V2TimConversation> data = await TencentImSDKPlugin
        .v2TIMManager
        .getConversationManager()
        .getConversation(conversationID: conversationID);
    String _msgID;
    int _type = 0;
    String _groupID = '';
    String _userID = '';

    if (data.code == 0) {
      if (data.data.lastMessage != null) {
        _msgID = data.data.lastMessage.msgID;
      }
      _type = data.data.type;
      // _groupID = data.data!.groupID!;
      _userID = data.data.userID;
      _conversation = data.data;
      print("_type: ${_type}");
      print('_userID: ${_userID}');
      print('_groupID: ${_groupID}');

      setState(() {
        type = _type;
        lastMessageId = _msgID;
        groupID = _groupID;
        userID = _userID;
        righTopIcon = _type == 1
            ? Icon(
                Icons.more_vert_rounded,
                color: Colors.black,
              )
            : Icon(
                Icons.supervisor_account,
                color: Colors.lightBlue,
              );
      });
    }

    //判断会话类型，c2c or group

    if (_type == 1) {
      // c2c
      TencentImSDKPlugin.v2TIMManager
          .getMessageManager()
          .getC2CHistoryMessageList(
            userID: _userID,
            count: count,
          )
          .then((listRes) {
        if (listRes.code == 0) {
          listRes.data.forEach((element) {
            print("消息：：：${element.toJson()}");
          });
          List<V2TimMessage> list = listRes.data;
          if (list == null || list.length == 0) {
            print('没有消息啊！！！');
            list = new List.empty();
          }
          print("conversationID $conversationID 消息数量 ${listRes.data.length}");
          Provider.of<CurrentMessageListModel>(context, listen: false)
              .addMessage(conversationID, list);

          Map<String, List<V2TimMessage>> _messageMap =
              Provider.of<CurrentMessageListModel>(context, listen: false)
                  .messageMap;
          setState(() {
            _messages = _messageMap[conversationID];
          });
        } else {
          print('conversationID 获取历史消息失败 ${listRes.desc}');
        }
      });
    } else if (_type == 2) {
      // group
      TencentImSDKPlugin.v2TIMManager
          .getMessageManager()
          .getGroupHistoryMessageList(
            groupID: _groupID,
            count: count,
          )
          .then((listRes) {
        if (listRes.code == 0) {
          print(
              "conversationID listRes.data ${listRes.data.length} $_groupID ");
          List<V2TimMessage> list = listRes.data;
          if (list == null || list.length == 0) {
            print('conversationID 没有消息啊！！！');
            list = new List.empty();
          } else {
            Provider.of<CurrentMessageListModel>(context, listen: false)
                .addMessage(conversationID, list);
            Map<String, List<V2TimMessage>> _messageMap =
                Provider.of<CurrentMessageListModel>(context, listen: false)
                    .messageMap;
            setState(() {
              _messages = _messageMap[conversationID];
            });
          }
          print("conversationID ${conversationID} 消息数量 ${listRes.data.length}");
        } else {
          print('conversationID 获取历史消息失败');
        }
      });
    }
  }

  /// 加载消息
  _onLoadMessages() async {
    print("数据  ：：：：" + count.toString());
    Map<String, List<V2TimMessage>> _messageMap =
        Provider.of<CurrentMessageListModel>(context, listen: false).messageMap;
    if (_messageMap[_conversation.conversationID] != null) {
      print("===================在这里：：：：" + _selfUser.toJson().toString());
      setState(() {
        _messages = _messageMap[_conversation.conversationID];
      });
      bool hasNoRead = _messages.any((element) {
        return !element.isSelf && !element.isRead;
      });
      if (hasNoRead) {
        print("设置个人会话已读");
        print(
            "设置个人会话已读设置个人会话已读设置个人会话已读设置个人会话已读设置个人会话已读设置个人会话已读设置个人会话已读设置个人会话已读设置个人会话已读设置个人会话已读");
        TencentImSDKPlugin.v2TIMManager
            .getMessageManager()
            .markC2CMessageAsRead(userID: _conversation.userID)
            .then((res) {
          if (res.code == 0) {
            print("设置个人会话已读 成功");
          } else {
            print("设置个人会话已读 失败");
          }
        });
      } else {
        print("没有未读");
      }
    } else {
      // if () {
      print("在这里：：：：" + _selfUser.toJson().toString());
      TencentImSDKPlugin.v2TIMManager
          .getMessageManager()
          .getC2CHistoryMessageList(
            userID: _conversation.userID,
            count: count,
          )
          .then((listRes) {
        if (listRes.code == 0) {
          var list = listRes.data;
          if (list.length == 0) {
            print('没有消息啊！！！');
            list = List.empty(growable: true);
          }
          listRes.data.forEach((element) {
            print("数据在这里:::${element.toJson()}");
          });
          print("conversationID $conversationID 消息数量 ${listRes.data.length}");
          Provider.of<CurrentMessageListModel>(context, listen: false)
              .addMessage(_conversation.conversationID, list);
          Map<String, List<V2TimMessage>> _messageMap =
              Provider.of<CurrentMessageListModel>(context, listen: false)
                  .messageMap;
          setState(() {
            _messages = _messageMap[_conversation.conversationID];
          });

          bool hasNoRead = _messages.any((element) {
            return !element.isSelf && !element.isRead;
          });
          if (hasNoRead) {
            print("设置个人会话已读");
            print(
                "设置个人会话已读设置个人会话已读设置个人会话已读设置个人会话已读设置个人会话已读设置个人会话已读设置个人会话已读设置个人会话已读设置个人会话已读设置个人会话已读");
            TencentImSDKPlugin.v2TIMManager
                .getMessageManager()
                .markC2CMessageAsRead(userID: _conversation.userID)
                .then((res) {
              if (res.code == 0) {
                print("设置个人会话已读 成功");
              } else {
                print("设置个人会话已读 失败");
              }
            });
          } else {
            print("没有未读");
          }
        } else {
          print('conversationID 获取历史消息失败 ${listRes.desc}');
        }
      });
    }
    print("在这里：：：：" + _selfUser.toJson().toString());
    TencentImSDKPlugin.v2TIMManager
        .getMessageManager()
        .getC2CHistoryMessageList(
          userID: _conversation.userID,
          count: count,
        )
        .then((listRes) {
      if (listRes.code == 0) {
        var list = listRes.data;
        if (list.length == 0) {
          print('没有消息啊！！！');
          list = List.empty(growable: true);
        }
        listRes.data.forEach((element) {
          print("数据在这里:::${element.toJson()}");
        });
        print("conversationID $conversationID 消息数量 ${listRes.data.length}");
        Provider.of<CurrentMessageListModel>(context, listen: false)
            .addMessage(_conversation.conversationID, list);
        Map<String, List<V2TimMessage>> _messageMap =
            Provider.of<CurrentMessageListModel>(context, listen: false)
                .messageMap;
        setState(() {
          _messages = _messageMap[_conversation.conversationID];
        });

        bool hasNoRead = _messages.any((element) {
          return !element.isSelf && !element.isRead;
        });
        if (hasNoRead) {
          print("设置个人会话已读");
          print(
              "设置个人会话已读设置个人会话已读设置个人会话已读设置个人会话已读设置个人会话已读设置个人会话已读设置个人会话已读设置个人会话已读设置个人会话已读设置个人会话已读");
          TencentImSDKPlugin.v2TIMManager
              .getMessageManager()
              .markC2CMessageAsRead(userID: _conversation.userID)
              .then((res) {
            if (res.code == 0) {
              print("设置个人会话已读 成功");
            } else {
              print("设置个人会话已读 失败");
            }
          });
        } else {
          print("没有未读");
        }
      } else {
        print('conversationID 获取历史消息失败 ${listRes.desc}');
      }
    });
  }

  ///已读
  setAllReady() {
    TencentImSDKPlugin.v2TIMManager
        .getMessageManager()
        .markC2CMessageAsRead(userID: userID);
  }

  ///发送图片
  _imagesSelect() async {
    _controller.jumpTo(_controller.position.minScrollExtent);
    setAllReady();
    File file;
    await _handleCameraAndMic();
    final List<AssetEntity> assets = await AssetPicker.pickAssets(context);
    if (assets.isEmpty) {
      return;
    }
    EasyLoading.showToast("发送中...");
    assets.forEach((element) async {
      file = await element.originFile;
      print("path=========" + element.title);
      await TencentImSDKPlugin.v2TIMManager
          .getMessageManager()
          .sendImageMessage(
              imagePath: file.path,
              receiver: userID,
              offlinePushInfo:
                  OfflinePushInfo(title: widget.nickName, desc: "[图片]"))
          .then((value) {
        List<V2TimMessage> list = new List.empty(growable: true);
        if (value.code == 0) {
          V2TimMessage msg = value.data;
          list.add(msg);
          Provider.of<CurrentMessageListModel>(context, listen: false)
              .addMessage(conversationID, list);
          Map<String, List<V2TimMessage>> _messageMap =
              Provider.of<CurrentMessageListModel>(context, listen: false)
                  .messageMap;
          setState(() {
            _messages = _messageMap[conversationID];
          });
          EasyLoading.dismiss();
          showToast("发送成功～");
        } else if (value.code == 2009) {
          EasyLoading.dismiss();
          sendNotFriendMessage(value);
          //showToast("20009");
          List<V2TimMessage> list = new List.empty(growable: true);
          V2TimMessage msg = value.data;
          list.add(msg);
          Provider.of<CurrentMessageListModel>(context, listen: false)
              .addMessage(conversationID, list);
          Map<String, List<V2TimMessage>> _messageMap =
              Provider.of<CurrentMessageListModel>(context, listen: false)
                  .messageMap;

          setState(() {
            _messages = _messageMap[conversationID];
          });
          showToast("发送失败");
        } else {
          EasyLoading.dismiss();
          sendNotFriendMessage(value);
          showToast("发送失败");
          List<V2TimMessage> list = new List.empty(growable: true);
          V2TimMessage msg = value.data;
          list.add(msg);
          Provider.of<CurrentMessageListModel>(context, listen: false)
              .addMessage(conversationID, list);
          Map<String, List<V2TimMessage>> _messageMap =
              Provider.of<CurrentMessageListModel>(context, listen: false)
                  .messageMap;
          //EasyLoading.dismiss();
          setState(() {
            _messages = _messageMap[conversationID];
          });
        }
      });
    });
    _controller.jumpTo(_controller.position.minScrollExtent);
    Map<String, List<V2TimMessage>> _messageMap =
        Provider.of<CurrentMessageListModel>(context, listen: false).messageMap;
    //EasyLoading.dismiss();
    setState(() {
      _messages = _messageMap[conversationID];
    });
  }

  ///发送视频
  _videoSelect() async {
    _controller.jumpTo(_controller.position.minScrollExtent);
    VideoPlayerController _controllers;
    setAllReady();

    _handleCameraAndMic();

    final XFile pickedFile = await ImagePicker().pickVideo(
        source: ImageSource.gallery, maxDuration: const Duration(seconds: 10));
    String a = await pickedFile.toString();
    if (pickedFile == null) return;
    _controllers =
        VideoPlayerController.file(File.fromUri(Uri.file(pickedFile.path)))
          ..initialize();

    print("===================在这" +
        TimeUtil.formatDuration(_controllers.value.duration));

    // 获得视频缩略图
    String thumb = await VideoThumbnail.thumbnailFile(
      video: pickedFile.path,
      thumbnailPath: _tempPath,
      imageFormat: ImageFormat.JPEG,
      quality: 40,
    );

    // 获得控制器并获得视频时长
    VideoPlayerController playerController =
        VideoPlayerController.file(File(pickedFile.path));
    await playerController.initialize();
    int duration = playerController.value.duration.inSeconds;

    print("视频路径" + pickedFile.path);
    EasyLoading.showToast("发送视频中..");
    V2TimValueCallback<V2TimMessage> res = await TencentImSDKPlugin.v2TIMManager
        .getMessageManager()
        .sendVideoMessage(
            videoFilePath: pickedFile.path,
            receiver: userID,
            duration: duration,
            type: "mp4",
            snapshotPath: thumb,
            offlinePushInfo:
                OfflinePushInfo(title: widget.nickName, desc: "[视频]"));

    List<V2TimMessage> list = new List.empty(growable: true);

    if (res.code == 0) {
      V2TimMessage msg = res.data;
      list.add(msg);
      Provider.of<CurrentMessageListModel>(context, listen: false)
          .addMessage(conversationID, list);
      Map<String, List<V2TimMessage>> _messageMap =
          Provider.of<CurrentMessageListModel>(context, listen: false)
              .messageMap;
      setState(() {
        _messages = _messageMap[conversationID];
      });
      EasyLoading.dismiss();
      showToast("发送视频成功！");
    } else if (res.code == 2009) {
      EasyLoading.dismiss();
      sendNotFriendMessage(res);
      //showToast("20009");
      List<V2TimMessage> list = new List.empty(growable: true);
      V2TimMessage msg = res.data;
      list.add(msg);
      Provider.of<CurrentMessageListModel>(context, listen: false)
          .addMessage(conversationID, list);
      Map<String, List<V2TimMessage>> _messageMap =
          Provider.of<CurrentMessageListModel>(context, listen: false)
              .messageMap;

      setState(() {
        _messages = _messageMap[conversationID];
      });
      showToast("发送失败");
    } else {
      EasyLoading.dismiss();
      sendNotFriendMessage(res);
      showToast("发送失败");
      List<V2TimMessage> list = new List.empty(growable: true);
      V2TimMessage msg = res.data;
      list.add(msg);
      Provider.of<CurrentMessageListModel>(context, listen: false)
          .addMessage(conversationID, list);
      Map<String, List<V2TimMessage>> _messageMap =
          Provider.of<CurrentMessageListModel>(context, listen: false)
              .messageMap;
      //EasyLoading.dismiss();
      setState(() {
        _messages = _messageMap[conversationID];
      });
    }
  }

  ///拍照发送
  _photoSelect() async {
    setAllReady();
    _controller.jumpTo(_controller.position.minScrollExtent);
    final pickedFile = await ImagePicker().getImage(source: ImageSource.camera);
    if (pickedFile == null) return;
    EasyLoading.showToast("发送图片中..");
    // this._sendMessage(ImageMessageNode(path: pickedFile.path));
    V2TimValueCallback<V2TimMessage> res = await TencentImSDKPlugin.v2TIMManager
        .getMessageManager()
        .sendImageMessage(
            imagePath: pickedFile.path,
            receiver: userID,
            offlinePushInfo:
                OfflinePushInfo(title: widget.nickName, desc: "[图片]"));
    List<V2TimMessage> list = new List.empty(growable: true);

    if (res.code == 0) {
      V2TimMessage msg = res.data;
      list.add(msg);

      Provider.of<CurrentMessageListModel>(context, listen: false)
          .addMessage(conversationID, list);
      Map<String, List<V2TimMessage>> _messageMap =
          Provider.of<CurrentMessageListModel>(context, listen: false)
              .messageMap;
      setState(() {
        _messages = _messageMap[conversationID];
      });
      EasyLoading.dismiss();
      showToast("发送图片成功");
    } else if (res.code == 2009) {
      EasyLoading.dismiss();
      sendNotFriendMessage(res);
      //showToast("20009");
      List<V2TimMessage> list = new List.empty(growable: true);
      V2TimMessage msg = res.data;
      list.add(msg);
      Provider.of<CurrentMessageListModel>(context, listen: false)
          .addMessage(conversationID, list);
      Map<String, List<V2TimMessage>> _messageMap =
          Provider.of<CurrentMessageListModel>(context, listen: false)
              .messageMap;

      setState(() {
        _messages = _messageMap[conversationID];
      });
      showToast("发送失败");
    } else {
      EasyLoading.dismiss();
      sendNotFriendMessage(res);
      showToast("发送失败");
      List<V2TimMessage> list = new List.empty(growable: true);
      V2TimMessage msg = res.data;
      list.add(msg);
      Provider.of<CurrentMessageListModel>(context, listen: false)
          .addMessage(conversationID, list);
      Map<String, List<V2TimMessage>> _messageMap =
          Provider.of<CurrentMessageListModel>(context, listen: false)
              .messageMap;
      //EasyLoading.dismiss();
      setState(() {
        _messages = _messageMap[conversationID];
      });
    }
  }

  ///发送语音
  _soundSelect() async {
    setAllReady();
    _controller.jumpTo(_controller.position.minScrollExtent);
    if (flags) {
      if (filePath == null) return;
      EasyLoading.showToast("发送中..");
      V2TimValueCallback<V2TimMessage> res = await TencentImSDKPlugin
          .v2TIMManager
          .getMessageManager()
          .sendSoundMessage(
              soundPath: filePath,
              receiver: userID,
              duration: soundDur,
              offlinePushInfo:
                  OfflinePushInfo(title: widget.nickName, desc: "[语音]"));

      List<V2TimMessage> list = new List.empty(growable: true);
      V2TimMessage msg = res.data;
      if (res.code == 0) {
        EasyLoading.dismiss();
        toast("发送成功");
        list.add(msg);
        Provider.of<CurrentMessageListModel>(context, listen: false)
            .addMessage(conversationID, list);
        Map<String, List<V2TimMessage>> _messageMap =
            Provider.of<CurrentMessageListModel>(context, listen: false)
                .messageMap;
        setState(() {
          _messages = _messageMap[conversationID];
        });
      } else if (res.code == 2009) {
        EasyLoading.dismiss();
        sendNotFriendMessage(res);
        //showToast("20009");
        List<V2TimMessage> list = new List.empty(growable: true);
        V2TimMessage msg = res.data;
        list.add(msg);
        Provider.of<CurrentMessageListModel>(context, listen: false)
            .addMessage(conversationID, list);
        Map<String, List<V2TimMessage>> _messageMap =
            Provider.of<CurrentMessageListModel>(context, listen: false)
                .messageMap;

        setState(() {
          _messages = _messageMap[conversationID];
        });
        showToast("发送失败");
      } else {
        EasyLoading.dismiss();
        sendNotFriendMessage(res);
        showToast("发送失败");
        List<V2TimMessage> list = new List.empty(growable: true);
        V2TimMessage msg = res.data;
        list.add(msg);
        Provider.of<CurrentMessageListModel>(context, listen: false)
            .addMessage(conversationID, list);
        Map<String, List<V2TimMessage>> _messageMap =
            Provider.of<CurrentMessageListModel>(context, listen: false)
                .messageMap;
        //EasyLoading.dismiss();
        setState(() {
          _messages = _messageMap[conversationID];
        });
      }
    }
  }

  ///申请图库权限
  _handleCameraAndMic() async {
    //申请权限

    bool a = await Permission.photos.request().isGranted;
    print(a);
    if (a == true) {
      print(a);
      print("已经打开");
    } else {
      showToast("请打开图库权限");
      await Future.delayed(Duration(seconds: 1));
      print(a);
      openAppSettings();
    }

//
  }

  /// 发送文字
  _sendMessage(value) async {
    setAllReady();
    if (value == null || value == "".trim()) {
      return showToast("不能发送空消息");
    }
    _controller.jumpTo(_controller.position.minScrollExtent);
    _textEditingController.text = "";
    //EasyLoading.show(status: "发送的消息为:  ${value}");
    V2TimValueCallback<V2TimMessage> res = await TencentImSDKPlugin.v2TIMManager
        .getMessageManager()
        .sendTextMessage(
            text: value,
            receiver: userID,
            offlinePushInfo:
                OfflinePushInfo(title: widget.nickName, desc: value));
    print("commint!!!!!!!!!!!!!!!!!!!!!!!!");
    print(res.data.toJson());

    if (res.code == 0) {
      // _messages.insert(_messages.length, res.data);
      List<V2TimMessage> list = new List.empty(growable: true);
      V2TimMessage msg = res.data;
      list.add(msg);
      Provider.of<CurrentMessageListModel>(context, listen: false)
          .addMessage(conversationID, list);
      Map<String, List<V2TimMessage>> _messageMap =
          Provider.of<CurrentMessageListModel>(context, listen: false)
              .messageMap;
      //EasyLoading.dismiss();
      setState(() {
        _messages = _messageMap[conversationID];
      });
    } else if (res.code == 2009) {
      //EasyLoading.dismiss();
      sendNotFriendMessage(res);
      showToast("20009");
      List<V2TimMessage> list = new List.empty(growable: true);
      V2TimMessage msg = res.data;
      list.add(msg);
      Provider.of<CurrentMessageListModel>(context, listen: false)
          .addMessage(conversationID, list);
      Map<String, List<V2TimMessage>> _messageMap =
          Provider.of<CurrentMessageListModel>(context, listen: false)
              .messageMap;
      //EasyLoading.dismiss();
      setState(() {
        _messages = _messageMap[conversationID];
      });
      showToast("发送失败");
    } else {
      sendNotFriendMessage(res);
      showToast("发送失败");
      List<V2TimMessage> list = new List.empty(growable: true);
      V2TimMessage msg = res.data;
      list.add(msg);
      Provider.of<CurrentMessageListModel>(context, listen: false)
          .addMessage(conversationID, list);
      Map<String, List<V2TimMessage>> _messageMap =
          Provider.of<CurrentMessageListModel>(context, listen: false)
              .messageMap;
      //EasyLoading.dismiss();
      setState(() {
        _messages = _messageMap[conversationID];
      });
    }
  }

  ///好友状态检查 发送本地消息
  sendNotFriendMessage(V2TimValueCallback<V2TimMessage> res) async {
    V2TimValueCallback<V2TimMessage> re = await TencentImSDKPlugin
        .v2TIMManager.v2TIMMessageManager
        .insertC2CMessageToLocalStorage(
            data: "对方开启了好友验证，您可以重新添加对方为好友",
            userID: userID,
            sender: res.data.sender);
    await TencentImSDKPlugin.v2TIMManager.v2TIMMessageManager
        .setLocalCustomInt(msgID: re.data.msgID, localCustomInt: 1);

    List<V2TimMessage> list = new List.empty(growable: true);
    V2TimMessage msg = re.data;
    re.data.localCustomInt = 1;
    list.add(msg);
    Provider.of<CurrentMessageListModel>(context, listen: false)
        .addMessage(conversationID, list);
    Map<String, List<V2TimMessage>> _messageMap =
        Provider.of<CurrentMessageListModel>(context, listen: false).messageMap;
    //EasyLoading.dismiss();
    setState(() {
      _messages = _messageMap[conversationID];
    });
  }

  ///加载更多消息
  _loadMoreData() async {
    count += 30;
    // if () {
    print("在这里：：：：" + _selfUser.toJson().toString());
    TencentImSDKPlugin.v2TIMManager
        .getMessageManager()
        .getC2CHistoryMessageList(
          userID: userID,
          count: count,
        )
        .then((listRes) {
      if (listRes.code == 0) {
        var list = listRes.data;

        if (list.length == 0) {
          print('没有消息啊！！！');
          list = List.empty(growable: true);
        }

        listRes.data.forEach((element) {
          print("数据在这里:::${element.toJson()}");
        });
        print("conversationID $conversationID 消息数量 ${listRes.data.length}");
        Provider.of<CurrentMessageListModel>(context, listen: false)
            .addMessage(_conversation.conversationID, list);
        Map<String, List<V2TimMessage>> _messageMap =
            Provider.of<CurrentMessageListModel>(context, listen: false)
                .messageMap;
        setState(() {
          _messages = _messageMap[_conversation.conversationID];
        });
      }
    });
  }

  ///刷新  加载更多消息
  Future<void> _onRefresh() async {
    count += 30;

    V2TimValueCallback<V2TimConversation> data = await TencentImSDKPlugin
        .v2TIMManager
        .getConversationManager()
        .getConversation(conversationID: conversationID);
    String _msgID;
    int _type = 0;
    String _groupID = '';
    String _userID = '';

    if (data.code == 0) {
      if (data.data.lastMessage != null) {
        _msgID = data.data.lastMessage.msgID;
      }
      _type = data.data.type;
      // _groupID = data.data!.groupID!;
      _userID = data.data.userID;
      _conversation = data.data;
      print("_type: ${_type}");
      print('_userID: ${_userID}');
      print('_groupID: ${_groupID}');

      setState(() {
        type = _type;
        lastMessageId = _msgID;
        groupID = _groupID;
        userID = _userID;
        righTopIcon = _type == 1
            ? Icon(
                Icons.more_vert_rounded,
                color: Colors.black,
              )
            : Icon(
                Icons.supervisor_account,
                color: Colors.lightBlue,
              );
      });
    }

    //判断会话类型，c2c or group

    if (_type == 1) {
      // c2c
      TencentImSDKPlugin.v2TIMManager
          .getMessageManager()
          .getC2CHistoryMessageList(
            userID: _userID,
            count: count,
          )
          .then((listRes) {
        if (listRes.code == 0) {
          listRes.data.forEach((element) {
            print("消息：：：${element.toJson()}");
          });
          List<V2TimMessage> list = listRes.data;
          if (list == null || list.length == 0) {
            print('没有消息啊！！！');
            list = new List.empty();
          }
          print("conversationID $conversationID 消息数量 ${listRes.data.length}");
          Provider.of<CurrentMessageListModel>(context, listen: false)
              .addMessage(conversationID, list);

          Map<String, List<V2TimMessage>> _messageMap =
              Provider.of<CurrentMessageListModel>(context, listen: false)
                  .messageMap;
          setState(() {
            _messages = _messageMap[conversationID];
          });
        } else {
          print('conversationID 获取历史消息失败 ${listRes.desc}');
        }
      });
    } else if (_type == 2) {
      // group
      TencentImSDKPlugin.v2TIMManager
          .getMessageManager()
          .getGroupHistoryMessageList(
            groupID: _groupID,
            count: count,
          )
          .then((listRes) {
        if (listRes.code == 0) {
          print(
              "conversationID listRes.data ${listRes.data.length} $_groupID ");
          List<V2TimMessage> list = listRes.data;
          if (list == null || list.length == 0) {
            print('conversationID 没有消息啊！！！');
            list = new List.empty();
          } else {
            Provider.of<CurrentMessageListModel>(context, listen: false)
                .addMessage(conversationID, list);
            Map<String, List<V2TimMessage>> _messageMap =
                Provider.of<CurrentMessageListModel>(context, listen: false)
                    .messageMap;
            setState(() {
              _messages = _messageMap[conversationID];
            });
          }
          print("conversationID ${conversationID} 消息数量 ${listRes.data.length}");
        } else {
          print('conversationID 获取历史消息失败');
        }
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: messageAppbar(),
      body: GestureDetector(
        onTap: () {
          FocusScope.of(context).requestFocus(FocusNode());
          setState(() {
            ///关闭emojo
            emojo = true;

            ///关闭 喜欢
            favorite = true;

            ///关闭更多
            flag = false;

            ///初始化图标
            bottomIcon = "images/message/表情.png";
            leftIcon = "images/message/语音.png";

            ///关闭语音消息
            soundFlag = false;
          });
        },
        onPanDown: (_) {
          /// 列表滑动响应
          closeKeyboard(context);
        },
        onHorizontalDragUpdate: (details) {
          ///右滑关闭判断
          if (details.globalPosition.dx > 60 &&
              details.globalPosition.dx < 120) {
            Get.back();
          }
        },
        child: Container(
          color: ZdColor.rgba(237, 237, 237, 1),
          child: Column(
            children: [
              messageBody(),

              //发送框
              GetPlatform.isAndroid && _focusNode.hasFocus ||
                      _textEditingController.text != ''
                  ? Container(
                      color: ZdColor.rgba(246, 246, 246, 1),
                      child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Container(width: width(4)),
                            InkWell(
                              onTap: () {
                                setState(() {
                                  _controller.jumpTo(
                                      _controller.position.minScrollExtent);
                                  soundFlag = !soundFlag;
                                  favorite = true;
                                  emojo = true;
                                  flag = false;
                                  flagBootom = true;
                                  bottomIcon = "images/message/表情.png";
                                  if (soundFlag) {
                                    leftIcon = "images/message/键盘.png";
                                  } else {
                                    _controller.jumpTo(
                                        _controller.position.minScrollExtent);
                                    leftIcon = "images/message/语音.png";
                                  }
                                });
                              },
                              child: Container(
                                height: 30,
                                width: width(28),
                                child: Image.asset(
                                  leftIcon,
                                  fit: BoxFit.cover,
                                  height: 22,
                                  width: width(19),
                                ),
                              ),
                            ),
                            Container(width: 8),
                            soundFlag
                                ? sendVoiceStyle(context)
                                : sendMessageStyle(context),
                            Container(width: 8),
                            InkWell(
                              onTap: () {
                                setState(() {
                                  if (_focusNode.hasFocus || flag) {
                                    _focusNode.unfocus();
                                    flag = false;
                                    flagBootom = false;
                                    showToast("images/message/键盘.png");

                                    setState(() {
                                      _controller.jumpTo(
                                          _controller.position.minScrollExtent);
                                      emojo = false;
                                      bottomIcon = "images/message/键盘.png";
                                      leftIcon = "images/message/语音.png";
                                      soundFlag = false;
                                    });
                                  } else {
                                    if (!emojo) {
                                      // showToast("1");

                                      emojo = true;
                                      bottomIcon = "images/message/表情.png";
                                    } else if (emojo) {
                                      //showToast("2");
                                      emojo = false;
                                      soundFlag = false;
                                      leftIcon = "images/message/语音.png";
                                      bottomIcon = "images/message/键盘.png";
                                    }
                                    flagBootom = true;
                                    _controller.jumpTo(
                                        _controller.position.minScrollExtent);
                                    favorite = true;
                                    flag = false;
                                    setState(() {});
                                  }
                                });
                              },
                              child: Container(
                                height: 30,
                                width: width(28),
                                child: Image.asset(
                                  bottomIcon,
                                  fit: BoxFit.cover,
                                  height: width(22),
                                  width: width(22),
                                ),
                              ),
                            ),
                            SizedBox(
                              width: width(10),
                            ),
                            InkWell(
                              onTap: () {
                                _sendMessage(_textEditingController.text);
                              },
                              child: Container(
                                width: 50.w,
                                height: 30.w,
                                alignment: Alignment.center,
                                decoration: BoxDecoration(
                                    color: ZdColor.rgba(0, 220, 169, 1),
                                    borderRadius: BorderRadius.circular(6)),
                                child: Text(
                                  "发送",
                                  style: TextStyle(color: Colors.white),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    )
                  : Container(
                      color: ZdColor.rgba(246, 246, 246, 1),
                      child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Container(width: width(4)),
                            InkWell(
                              onTap: () {
                                setState(() {
                                  _controller.jumpTo(
                                      _controller.position.minScrollExtent);
                                  soundFlag = !soundFlag;
                                  favorite = true;
                                  emojo = true;
                                  flag = false;
                                  flagBootom = true;
                                  bottomIcon = "images/message/表情.png";
                                  if (soundFlag) {
                                    leftIcon = "images/message/键盘.png";
                                  } else {
                                    _controller.jumpTo(
                                        _controller.position.minScrollExtent);
                                    leftIcon = "images/message/语音.png";
                                  }
                                });
                              },
                              child: Container(
                                height: 30,
                                width: width(28),
                                child: Image.asset(
                                  leftIcon,
                                  fit: BoxFit.cover,
                                  height: 22,
                                  width: width(19),
                                ),
                              ),
                            ),
                            Container(width: 8),
                            soundFlag
                                ? sendVoiceStyle(context)
                                : sendMessageStyle(context),
                            Container(width: 8),
                            InkWell(
                              onTap: () {
                                setState(() {
                                  if (_focusNode.hasFocus || flag) {
                                    _focusNode.unfocus();
                                    flag = false;
                                    flagBootom = false;
                                    showToast("images/message/键盘.png");

                                    setState(() {
                                      _controller.jumpTo(
                                          _controller.position.minScrollExtent);
                                      emojo = false;
                                      bottomIcon = "images/message/键盘.png";
                                      leftIcon = "images/message/语音.png";
                                      soundFlag = false;
                                    });
                                  } else {
                                    if (!emojo) {
                                      // showToast("1");

                                      emojo = true;
                                      bottomIcon = "images/message/表情.png";
                                    } else if (emojo) {
                                      //showToast("2");
                                      emojo = false;
                                      soundFlag = false;
                                      leftIcon = "images/message/语音.png";
                                      bottomIcon = "images/message/键盘.png";
                                    }
                                    flagBootom = true;
                                    _controller.jumpTo(
                                        _controller.position.minScrollExtent);
                                    favorite = true;
                                    flag = false;
                                    setState(() {});
                                  }
                                });
                              },
                              child: Container(
                                height: 30,
                                width: width(28),
                                child: Image.asset(
                                  bottomIcon,
                                  fit: BoxFit.cover,
                                  height: width(22),
                                  width: width(22),
                                ),
                              ),
                            ),
                            SizedBox(
                              width: width(10),
                            ),
                            InkWell(
                              onTap: () {
                                if (!emojo) {
                                  setState(() {
                                    _controller.jumpTo(
                                        _controller.position.minScrollExtent);
                                    emojo = true;
                                  });
                                }
                                setState(() {
                                  _controller.jumpTo(
                                      _controller.position.minScrollExtent);
                                  flag = !flag;
                                  favorite = true;
                                  soundFlag = false;
                                  leftIcon = "images/message/语音.png";
                                  bottomIcon = "images/message/表情.png";
                                  _focusNode.unfocus();
                                });
                              },
                              child: Container(
                                height: 30,
                                width: width(28),
                                child: Image.asset(
                                  "images/增加.png",
                                  fit: BoxFit.cover,
                                  height: width(22),
                                  width: width(22),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
              flag ? openMore() : SizedBox(),
              emojoBody(),

              favoriteBody(),

              //底部危险距离颜色值
              Container(
                color: flag == true ||
                        checkMessage == false ||
                        favorite == false ||
                        emojo == false
                    ? null
                    : ZdColor.rgba(246, 246, 246, 1),
                height: MediaQuery.of(context).padding.bottom,
              )
            ],
          ),
        ),
      ),
    );
  }

  Expanded sendMessageStyle(BuildContext context) {
    return Expanded(
      child: Container(
        width: width(250),
        constraints: BoxConstraints(
          maxHeight: 40,
        ),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(6)),
          color: Colors.white,
        ),
        child: TextField(
          cursorColor: Colors.greenAccent,
          onSubmitted: (value) {
            _sendMessage(value);
            FocusScope.of(context).requestFocus(_focusNode);
          },
          controller: _textEditingController,
          focusNode: _focusNode,
          autofocus: false,
          textInputAction: TextInputAction.send,
          decoration: InputDecoration(
            border: InputBorder.none,
            contentPadding: EdgeInsets.only(
              left: 15,
              top: -8,
              bottom: 0,
              right: 15,
            ),
          ),
        ),
      ),
    );
  }

  Expanded sendVoiceStyle(BuildContext context) {
    return Expanded(
      child: GestureDetector(
        onLongPressStart: (e) {
          setState(() {
            _controller.jumpTo(_controller.position.minScrollExtent);
            isRecording = true;
            isSend = true;
          });
          print("anxia ");
          buildOverLayView(context);
          _requestAppDocumentsDirectory();
        },
        onLongPressEnd: (e) {
          if (e.localPosition.dx < 0 ||
              e.localPosition.dy < 0 ||
              e.localPosition.dy > 40) {
            print("滑动");

            flags = false;
            showToast("取消发送");
            try {
              if (overlayEntry != null) {
                overlayEntry.remove();
                overlayEntry = null;
              }
            } catch (err) {}
            setState(() {
              isRecording = true;
              isSend = true;
            });
            stop();
          } else {
            try {
              if (overlayEntry != null) {
                overlayEntry.remove();
                overlayEntry = null;
              }
            } catch (err) {}
            setState(() {
              isRecording = true;
              isSend = true;
              flags = true;
            });

            stop();
          }
        },
        child: Container(
            width: width(250),
            constraints: BoxConstraints(
              maxHeight: 40,
            ),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.all(Radius.circular(6)),
              color: Colors.white,
            ),
            alignment: Alignment.center,
            child: Text("按下发送")),
      ),
    );
  }

  Offstage favoriteBody() {
    return Offstage(
      offstage: favorite,
      child: Container(
          child: Column(
        children: [
          Container(
            height: 260,
            width: double.infinity,
            child: ListView(
              shrinkWrap: true,
              children: [
                Wrap(
                  children: widgetData,
                )
              ],
            ),
          ),
          Container(
            margin: EdgeInsets.only(left: 20.w),
            child: Row(
              children: [
                InkWell(
                  child: Container(
                    height: 40.w,
                    width: 40.w,
                    padding: EdgeInsets.all(10),
                    child: Image.asset(
                      "images/message/表情.png",
                      height: 22.w,
                      width: 22.w,
                    ),
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(6),
                      color: !emojo ? white : null,
                    ),
                  ),
                  onTap: () {
                    setState(() {
                      favorite = true;
                      emojo = false;
                    });
                  },
                ),
                InkWell(
                  onTap: () {
                    setState(() {
                      favorite = true;
                      emojo = true;
                    });
                  },
                  child: Container(
                      margin: EdgeInsets.only(left: width(10)),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(6),
                        color: !favorite ? white : null,
                      ),
                      height: 40.w,
                      width: 40.w,
                      alignment: Alignment.center,
                      child: Icon(Icons.favorite_outline_rounded)),
                ),
                InkWell(
                  onTap: () {
                    _sendMessage(_textEditingController != null
                        ? _textEditingController.text != null &&
                                _textEditingController.text != ""
                            ? _textEditingController.text
                            : ""
                        : "");
                  },
                  child: Container(
                    alignment: Alignment.center,
                    margin: EdgeInsets.only(
                        top: 11, bottom: 11, right: 15, left: 167.w),
                    height: 38,
                    width: ScreenUtil().setWidth(60),
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(6),
                      color: Color.fromRGBO(0, 220, 169, 1),
                    ),
                    child: Text(
                      "发送",
                      style: TextStyle(
                          color: Colors.white,
                          fontSize: ScreenUtil().setSp(14)),
                    ),
                  ),
                )
              ],
            ),
          ),
        ],
      )),
    );
  }

  Offstage emojoBody() {
    return Offstage(
      offstage: emojo,
      child: Column(
        children: [
          Container(
            height: 260,
            child: EmojiPicker(
                onEmojiSelected: (Category category, Emoji emoji) {
                  _onEmojiSelected(emoji);
                },
                onBackspacePressed: _onBackspacePressed,
                config: const Config(
                    columns: 7,
                    emojiSizeMax: 32.0,
                    verticalSpacing: 0,
                    horizontalSpacing: 0,
                    initCategory: Category.RECENT,
                    bgColor: Color(0xFFF2F2F2),
                    indicatorColor: Colors.blue,
                    iconColor: Colors.grey,
                    iconColorSelected: Colors.blue,
                    progressIndicatorColor: Colors.blue,
                    backspaceColor: Colors.blue,
                    showRecentsTab: true,
                    recentsLimit: 28,
                    noRecentsText: 'No Recents',
                    noRecentsStyle:
                        TextStyle(fontSize: 20, color: Colors.black26),
                    categoryIcons: CategoryIcons(),
                    buttonMode: ButtonMode.MATERIAL)),
          ),
          Container(
            margin: EdgeInsets.only(left: 20.w),
            child: Row(
              children: [
                InkWell(
                  child: Container(
                    height: 40.w,
                    width: 40.w,
                    padding: EdgeInsets.all(10),
                    child: Image.asset(
                      "images/message/表情.png",
                      height: 22.w,
                      width: 22.w,
                    ),
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(6),
                      color: !emojo ? white : null,
                    ),
                  ),
                  onTap: () {
                    setState(() {
                      emojo = false;
                    });
                  },
                ),
                InkWell(
                  onTap: () {
                    setState(() {
                      favorite = false;
                      //收藏 按键
                      getData();
                      emojo = true;
                    });
                  },
                  child: Container(
                      margin: EdgeInsets.only(left: width(10)),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(6),
                        color: !favorite ? white : null,
                      ),
                      height: 40.w,
                      width: 40.w,
                      alignment: Alignment.center,
                      child: Icon(Icons.favorite_outline_rounded)),
                ),
                InkWell(
                  onTap: () {
                    _sendMessage(_textEditingController != null
                        ? _textEditingController.text != null &&
                                _textEditingController.text != ""
                            ? _textEditingController.text
                            : ""
                        : "");
                  },
                  child: Container(
                    alignment: Alignment.center,
                    margin: EdgeInsets.only(
                        top: 11, bottom: 11, right: 15, left: 167.w),
                    height: 38,
                    width: ScreenUtil().setWidth(60),
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(6),
                      color: Color.fromRGBO(0, 220, 169, 1),
                    ),
                    child: Text(
                      "发送",
                      style: TextStyle(
                          color: Colors.white,
                          fontSize: ScreenUtil().setSp(14)),
                    ),
                  ),
                )
              ],
            ),
          ),
        ],
      ),
    );
  }

  Container openMore() {
    return Container(
      height: 257,
      color: ZdColor.rgba(237, 237, 237, 1),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              Column(
                children: [
                  InkWell(
                    onTap: _imagesSelect,
                    child: Container(
                      margin: EdgeInsets.only(
                        top: 20,
                      ),
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(10),
                        color: Colors.white,
                      ),
                      height: width(60),
                      width: width(60),
                      child: Image.asset(
                        "images/message/picture_fill.png",
                        height: width(23),
                        width: width(23),
                      ),
                    ),
                  ),
                  Container(
                    alignment: Alignment.center,
                    margin: EdgeInsets.only(top: 5),
                    child: Text(
                      "照片",
                      style: TextStyle(
                          fontSize: sp(12), color: ZdColor.rgba(85, 85, 85, 1)),
                    ),
                  )
                ],
              ),
              Column(
                children: [
                  InkWell(
                    onTap: _photoSelect,
                    child: Container(
                      margin: EdgeInsets.only(
                        top: 20,
                      ),
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(10),
                        color: Colors.white,
                      ),
                      height: width(60),
                      width: width(60),
                      child: Image.asset(
                        "images/message/camera_fill.png",
                        height: width(23),
                        width: width(23),
                      ),
                    ),
                  ),
                  Container(
                    alignment: Alignment.center,
                    margin: EdgeInsets.only(top: 5),
                    child: Text(
                      "拍照",
                      style: TextStyle(
                          fontSize: sp(12), color: ZdColor.rgba(85, 85, 85, 1)),
                    ),
                  )
                ],
              ),
              Column(
                children: [
                  InkWell(
                    onTap: _videoSelect,
                    child: Container(
                      margin: EdgeInsets.only(
                        top: 20,
                      ),
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(10),
                        color: Colors.white,
                      ),
                      height: width(60),
                      width: width(60),
                      child: Image.asset(
                        "images/message/video_fill.png",
                        height: width(23),
                        width: width(23),
                      ),
                    ),
                  ),
                  Container(
                    alignment: Alignment.center,
                    margin: EdgeInsets.only(top: 5),
                    child: Text(
                      "视频",
                      style: TextStyle(
                          fontSize: sp(12), color: ZdColor.rgba(85, 85, 85, 1)),
                    ),
                  )
                ],
              ),

              //TODO 暂时隐藏
              // Column(
              //   children: [
              //     Container(
              //       margin: EdgeInsets.only(
              //         top: 20,
              //       ),
              //       alignment: Alignment.center,
              //       decoration: BoxDecoration(
              //         borderRadius: BorderRadius.circular(10),
              //         color: Colors.white,
              //       ),
              //       height: width(60),
              //       width: width(60),
              //       child: Image.asset(
              //         "images/message/语音.png",
              //         height: width(23),
              //         width: width(23),
              //       ),
              //     ),
              //     Container(
              //       alignment: Alignment.center,
              //       margin: EdgeInsets.only(top: 5),
              //       child: Text(
              //         "语音通话",
              //         style: TextStyle(
              //             fontSize: sp(12),
              //             color: ZdColor.rgba(85, 85, 85, 1)),
              //       ),
              //     )
              //   ],
              // ),
              Column(
                children: [
                  InkWell(
                    onTap: () {
                      _openModalBottomSheet();
                    },
                    child: Container(
                      margin: EdgeInsets.only(
                        top: 20,
                      ),
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(10),
                        color: Colors.white,
                      ),
                      height: width(60),
                      width: width(60),
                      child: Image.asset(
                        "images/message/barrage_fill.png",
                        height: width(23),
                        width: width(23),
                      ),
                    ),
                  ),
                  InkWell(
                    onTap: () {},
                    child: Container(
                      alignment: Alignment.center,
                      margin: EdgeInsets.only(top: 5),
                      child: Text(
                        "常用语",
                        style: TextStyle(
                            fontSize: sp(12),
                            color: ZdColor.rgba(85, 85, 85, 1)),
                      ),
                    ),
                  )
                ],
              ),
            ],
          ),
          //TODO 暂时隐藏
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              // Column(
              //   children: [
              //     Container(
              //       margin: EdgeInsets.only(
              //         top: 20,
              //       ),
              //       alignment: Alignment.center,
              //       decoration: BoxDecoration(
              //         borderRadius: BorderRadius.circular(10),
              //         color: Colors.white,
              //       ),
              //       height: width(60),
              //       width: width(60),
              //       child: Image.asset(
              //         "images/message/coordinates_fill.png",
              //         height: width(23),
              //         width: width(23),
              //       ),
              //     ),
              //     Container(
              //       alignment: Alignment.center,
              //       margin: EdgeInsets.only(top: 5),
              //       child: Text(
              //         "位置",
              //         style: TextStyle(
              //             fontSize: sp(12),
              //             color: ZdColor.rgba(85, 85, 85, 1)),
              //       ),
              //     )
              //   ],
              // ),
              // Column(
              //   children: [
              //     Container(
              //       margin: EdgeInsets.only(
              //         top: 20,
              //       ),
              //       alignment: Alignment.center,
              //       decoration: BoxDecoration(
              //         borderRadius: BorderRadius.circular(10),
              //         color: Colors.white,
              //       ),
              //       height: width(60),
              //       width: width(60),
              //       child: Image.asset(
              //         "images/message/tasklist_fill.png",
              //         height: width(23),
              //         width: width(23),
              //       ),
              //     ),
              //     Container(
              //       alignment: Alignment.center,
              //       margin: EdgeInsets.only(top: 5),
              //       child: Text(
              //         "文件",
              //         style: TextStyle(
              //             fontSize: sp(12),
              //             color: ZdColor.rgba(85, 85, 85, 1)),
              //       ),
              //     )
              //   ],
              // ),

              Column(
                children: [
                  InkWell(
                    onTap: () {
                      Get.to(() => CollectPage());
                    },
                    child: Container(
                      margin: EdgeInsets.only(
                        top: 20,
                      ),
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(10),
                        color: Colors.white,
                      ),
                      height: width(60),
                      width: width(60),
                      child: Image.asset(
                        "images/message/manage_fill.png",
                        height: width(23),
                        width: width(23),
                      ),
                    ),
                  ),
                  Container(
                    alignment: Alignment.center,
                    margin: EdgeInsets.only(top: 5),
                    child: Text(
                      "我的收藏",
                      style: TextStyle(
                          fontSize: sp(12), color: ZdColor.rgba(85, 85, 85, 1)),
                    ),
                  )
                ],
              ),
              SizedBox(
                width: 60.w,
              ),
              SizedBox(
                width: 60.w,
              ),
              SizedBox(
                width: 60.w,
              ),
            ],
          ),
        ],
      ),
    );
  }

  Container messageBody() {
    return Container(
      child: Expanded(
        child: Container(
          decoration: BoxDecoration(
            image: DecorationImage(
                //TODO 背景图 服务器获取
                image: CachedNetworkImageProvider(
                  getIMBgImg() == "" ? "" : getIMBgImg(),
                ),
                fit: BoxFit.fitWidth),
          ),
          child: RefreshIndicator(
            onRefresh: _onRefresh,
            displacement: 40, //指示器显示时距顶部位置
            color: Colors.greenAccent, //指示器颜色，默认ThemeData.accentColor
            backgroundColor: Colors.white, //指示器背景颜色，默认ThemeData.canvasColor
            notificationPredicate:
                defaultScrollNotificationPredicate, //是否应处理滚动通知的检查（是否通知下拉刷新动作）
            child: MessageBodyWidget(
              conversationID,
              type,
              userID,
              groupID,
              _conversation,
              // refrsh: _onRefresh(),
              // refrsh: _getConversion(),
              messages: _messages,
              controller: _controller,
              name: (name) {
                // _name = name;
              },
            ),
          ),
        ),
      ),
    );
  }

  AppBar messageAppbar() {
    return AppBar(
      leading: InkWell(
        onTap: () {
          if (checkMessage) {
            Get.back();
          } else {
            setState(() {
              checkMessage = true;
            });
          }
        },
        child: checkMessage
            ? Icon(Icons.arrow_back_ios)
            : Container(
                alignment: Alignment.center,
                child: Text(
                  "取消",
                  textAlign: TextAlign.center,
                  style: TextStyle(fontSize: 15.sp),
                ),
              ),
      ),
      title: Text(_name),
      centerTitle: true,
      elevation: 0.5,
      actions: [
        _conversation == null
            ? null
            : IconButton(
                icon: Image.asset(
                  "images/message/更多.png",
                  fit: BoxFit.cover,
                  height: width(22),
                  width: width(22),
                ),
                onPressed: () {
                  Get.to(() => FriendInfoSettingPage(
                      conversation: _conversation, messages: _messages));
                },
              ),
        Container(width: 8),
      ]..removeWhere((element) => element == null),
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
